package com.sxhuayuan.parking.service.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sxhuayuan.parking.compenent.shiro.AccountType;
import com.sxhuayuan.parking.compenent.shiro.Principal;
import com.sxhuayuan.parking.dao.BaseDao;
import com.sxhuayuan.parking.dao.MemberDao;
import com.sxhuayuan.parking.entity.Member;
import com.sxhuayuan.parking.service.MemberService;

@Service("memberServiceImpl")
public class MemberServiceImpl extends BaseServiceImpl<Member, Long> implements MemberService {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	MemberDao memberDao;

	@Override
	public BaseDao<Member, Long> getDAO() {
		return memberDao;
	}

	@Override
	@Transactional(readOnly = true)
	public Member findByOpenId(String openId) {
		return memberDao.findByOpenid(openId);
	}

	@Override
	@Transactional(readOnly = true)
	public Member findByUnionid(String unionid) {
		return memberDao.findByUnionid(unionid);
	}

	@Override
	@Transactional(readOnly = true)
	public Member getCurrent() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null && subject.getPrincipal() != null) {
			Principal principal = (Principal) subject.getPrincipal();
			if (principal.getType() == AccountType.member) {
				return memberDao.findById(principal.getId()).get();
			}
		}
		return null;
	}

	@Transactional(readOnly = true)
	public String getCurrentName() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null && subject.getPrincipal() != null) {
			Principal principal = (Principal) subject.getPrincipal();
			if (principal.getType() == AccountType.member) {
				return principal.getUsername();
			}
		}
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public boolean isAuthenticated() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null && subject.getPrincipal() != null) {
			Principal principal = (Principal) subject.getPrincipal();
			if (principal.getType() == AccountType.member) {
				return subject.isAuthenticated();
			}
		}
		return false;
	}

}
